<template>
  <view class="container">
    <view class="banner">
      <image src="https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/shop_banner.jpg" style="width:100%" mode="widthFix"></image>
    </view>
    <view class="city-bar-container">
      <image class="location-icon" src="https://alicdn.joyballet.cn/eyemanager/wechat/shop_list_title.png" mode="widthFix"></image>
      <view class="city-bar" @click="openCitySelector">
        <text class="city-text">{{ currentCity || '定位中' }}</text>
      </view>
    </view>
    <view v-for="(shop, index) in shopList" :key="index" 
          class="product-card" 
          :class="{ 'selected-card': selectedShopId === shop.id }" 
          @click="selectShop(shop.id)">
      <view class="shop-left" style="display: flex; align-items: center;">
        <image src="https://alicdn.joyballet.cn/eyemanager/wechat/shop_icon.png" style="width: 50px;" mode="widthFix"></image>
      </view>
      <view class="shop-right">
          <view class="shop-name" style="font-size: 24px;">{{ shop.name }} 
            <image src="https://alicdn.joyballet.cn/eyemanager/wechat/shop_name_right.png" style="vertical-align: middle;width: 7px;margin-left: 10px;" class="vertical-middle" mode="widthFix"></image>
          </view>
          <view class="shop-tags">
              <text class="tag" style="color: #B9751C;background-color: #FDE6C8;">{{ shop.tag1 || '清晰' }}</text>
              <text class="tag" style="color: #2D7D9D;background-color: #C9E8F5;">{{ shop.tag2 || '控轴' }}</text>
              <text class="tag" style="color: #1A918A;background-color: #C6E6E9;">{{ shop.tag3 || '舒适' }}</text>
          </view>
          <view class="shop-time" style="color:#EBA540;">
            <image src="https://alicdn.joyballet.cn/eyemanager/wechat/shop_lock.png" class="text-icon"  mode="widthFix"></image>
            <text class="iconfont icon-clock"></text> 接诊时间： {{ shop.acceptTime || '周一至周日 10:00-20:00' }}</view>
          <view class="shop-address" style="color: #B4B4B4;">
            <image src="https://alicdn.joyballet.cn/eyemanager/wechat/shop_location.png" class="text-icon"  mode="widthFix"></image>
            <text class="iconfont icon-map"></text> {{ shop.address }}
          </view>
          <view class="shop-distance" style="color: #008F86;text-decoration: underline;" @tap="navigateToShop(shop.latitude, shop.longitude, shop.name)">
            <image src="https://alicdn.joyballet.cn/eyemanager/wechat/shop_distance.png" class="text-icon"  mode="widthFix"></image>
            <text class="iconfont icon-location"></text> 距离您 {{ shop.distance ? (shop.distance >= 1000 ? Math.floor(shop.distance / 1000) + ' 公里' : shop.distance + ' 米') : '计算中' }}
          </view>
      </view>
    </view>
    <view v-if="shopList.length == 0" style="text-align: center;">
       <view class="product-card">
        <view class="shop-left" style="display: flex; align-items: center;">
          <image src="https://alicdn.joyballet.cn/eyemanager/wechat/shop_icon.png" style="width: 50px;" mode="widthFix"></image>
        </view>
        <view class="shop-right">
          <view class="shop-name" style="font-size: 24px;">该城市暂无店铺~</view>
        </view>
      </view>        
    </view>
    <view class="city-selector-mask" v-if="showCitySelector" @click="closeCitySelector"></view>
    <view class="city-selector" v-if="showCitySelector">
      <view class="selector-header">
        <text class="header-title">选择城市</text>
        <text class="close-btn" @click="closeCitySelector">×</text>
      </view>
      <view class="city-list">
        <view v-for="(city, index) in cityList" :key="city.value" class="city-item" @click="selectCity(city.label)">
          <text>{{ city.label }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    components: {},
    props: {},
    data() {
      return {
        shopList: [],
        currentCity: '',
        latitude: '',
        longitude: '',
        latitude2: '',
        longitude2: '',
        selectedShopId: null, 
        useLocation: true,
        cityList: [],
        showCitySelector: false
      };
    },
    onLoad() {
      // 页面加载时获取定位
      this.getUserLocation();
      this.fetchCityList()
    },
    onShow() {
      // this.fetchShopList()
    },
    onShareAppMessage() {
      return {
        title: '青少年近视防控领先方案', // 分享标题
        path: '/pages/index/report', // 分享路径
        imageUrl: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/wechat_share.png', // 分享图片，这里使用生成的二维码图片
        success: function(res) {
          // 转发成功
          console.log("转发成功:");
        },
        fail: function(res) {
          // 转发失败
          console.log("转发失败:");
        }
      }
    },
    methods: {
      selectShop(shopId) {
        this.selectedShopId = shopId;
        // this.$tools.routerTo('/pages/index/appointWeek?shopId=' + shopId, 'navigateTo', 'none')
      },
      fetchCityList() {
        const that = this
        this.$http.GET('/app/order/order/getCityList', {}, function (res) {
          that.cityList = res.data
        })
      },
      fetchShopList() {
        const that = this
        try {
          this.$http.GET('/app/order/order/getShopList', {
            cityName: this.currentCity
          }, function (res) {
            that.shopList = res.data
            // 根据店铺经纬度去计算店铺距离
            that.shopList.forEach(shop => {
              // 只计算一个店铺
              console.log('shopid', shop.id)
              // if (shop.id == 4) {
                console.log('店铺经纬度', shop.latitude, shop.longitude)
                that.latitude2 = shop.latitude
                that.longitude2 = shop.longitude
                if (that.useLocation) {
                  shop.distance = that.calculateDistance(shop)
                }
              // }
            })
          })
        } catch (error) {
          console.error('获取店铺列表失败:', error)
        }
      },
      calculateDistance(shop) {
        const that = this
        // 计算距离
        const distance = this.getDistance(that.latitude, that.longitude, shop.latitude, shop.longitude, shop.id);
        console.log('距离', distance)
        return distance;
      },
      // 计算距离
      getDistance(lat1, lon1, lat2, lon2, shopId) {
        const that = this;
        // 使用腾讯地图API进行逆地理编码
        // 注意：需要替换为您自己的KEY
        const key = 'b4f3f6e5e0641ece42a9ad8353c822e1';
        // https://restapi.amap.com/v3/assistant/coordinate/convert?locations=116.481499,39.990475&coordsys=gps&output=xml&key=<用户的key>
        const url = `https://restapi.amap.com/v5/direction/driving?origin=${lon1},${lat1}&destination=${lon2},${lat2}&key=${key}`;
        uni.request({
          url: url,
          success(res) {
            console.log('计算距离2', res, res.data.infocode, res.data.route, res.data.route.paths[0].distance);
            if (res.data.infocode === "10000") {
              // 遍历店铺列表，更新选中店铺的距离
              that.shopList.forEach(shop => {
                if (shop.id == shopId) {
                  // 拿到距离后需要重新渲染距离
                  shop.distance = res.data.route.paths[0].distance
                  that.$set(that.shopList, that.shopList.indexOf(shop), shop)
                }
              })
              return true
            } else {
              console.error('解析城市失败:', res.data.info);
            }
          },
          fail(err) {
            console.error('请求城市信息失败:', err);
            that.currentCity = '网络异常，无法获取城市信息';
          }
        });
      },
      navigateToShop(latitude, longitude, name) {
        // 检查经纬度是否存在
        if (!latitude || !longitude) {
          uni.showToast({
            title: '该店铺暂无定位信息',
            icon: 'none'
          });
          return;
        }

        // 使用微信内置地图导航
        uni.openLocation({
          latitude: Number(latitude),
          longitude: Number(longitude),
          name: name,
          scale: 18
        });
      },
      // 获取用户位置
      getUserLocation() {
        const that = this;
        uni.getLocation({
          type: 'gcj02',
          success(res) {
            // 获取设备信息判断是否为苹果手机
            const systemInfo = uni.getSystemInfoSync();
            const isIOS = systemInfo.platform === 'ios';
            
            // 如果是苹果手机，则调转经纬度
            // if (isIOS) {
            //   that.latitude = res.longitude;
            //   that.longitude = res.latitude;
            // } else {
            //   that.latitude = res.latitude;
            //   that.longitude = res.longitude;
            // }
            that.latitude = res.latitude;
            that.longitude = res.longitude;
            console.log('用户位置', that.latitude, that.longitude, that.shopList, that.shopList.length)
            if (that.useLocation) {
              that.getCityByLocation(); 
            }
            // that.getDistance(that.latitude, that.longitude, that.latitude2, that.longitude2)
            // that.fetchShopList()
          },
          fail(err) {
            console.error('获取位置失败:', err);
            that.currentCity = '定位失败，请授权后重试';
            // 提示用户授权
            uni.showModal({
              title: '提示',
              content: '需要您授权位置信息以获取当前城市',
              success(modalRes) {
                if (modalRes.confirm) {
                  uni.openSetting({
                    success(settingRes) {
                      if (settingRes.authSetting['scope.userLocation']) {
                        that.getUserLocation();
                      }
                    }
                  });
                }
              }
            });
          }
        });
      },
      // 根据经纬度获取城市
      getCityByLocation() {
        const that = this;
        // 使用腾讯地图API进行逆地理编码
        // 注意：需要替换为您自己的KEY
        const key = 'b4f3f6e5e0641ece42a9ad8353c822e1';
        // https://restapi.amap.com/v3/assistant/coordinate/convert?locations=116.481499,39.990475&coordsys=gps&output=xml&key=<用户的key>
        const url = `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${that.longitude},${that.latitude}&key=${key}&radius=1000&extensions=all `;
        uni.request({
          url: url,
          success(res) {
            console.log('高德地图经纬度解析城市', res)
            if (res.data.infocode === "10000") {
              let city = res.data.regeocode.addressComponent.city;
              if (city.length == 0) {
                city = res.data.regeocode.addressComponent.province
              }
              console.log(city, res.data.regeocode.addressComponent.city, res.data.regeocode.addressComponent.province)
              that.currentCity = city;
              that.fetchShopList()
            } else {
              console.error('解析城市失败:', res.data.info);
              that.currentCity = '未能获取城市信息';
            }
          },
          fail(err) {
            console.error('请求城市信息失败:', err);
            that.currentCity = '网络异常，无法获取城市信息';
          }
        });
      },
      openCitySelector() {
        this.showCitySelector = true;
        console.log('选择城市', this.showCitySelector, this.cityList)
      },
      // 关闭城市选择弹窗
      closeCitySelector() {
        this.showCitySelector = false;
      },
      // 选择城市
      selectCity(city) {
        console.log('selectCity', city)
        this.currentCity = city;
        this.closeCitySelector();
        // 重新请求店铺列表
        this.fetchShopList();
      },
    },
  };
</script>

<style scoped lang="css">
.text-icon {
  width: 15px;
  margin-right: 5px;
}
.banner {
  width: 100%;
}
.container {
  width: 100%; /* 宽度铺满屏幕 */
  height: 100vh; /* 高度铺满视口 */
  min-height: 100%; /* 确保至少填满内容高度 */
  background-color: #F9F9F9; /* 背景颜色 */
  margin: 0; /* 移除默认外边距 */
  padding: 0; /* 移除默认内边距 */
  box-sizing: border-box; /* 确保内边距和边框不增加总宽度 */
  /* 移除顶部内边距，因为城市栏不再固定在顶部 */
}

/* 城市栏容器 - 用于控制城市栏的位置 */
.city-bar-container {
  width: 100%;
  padding: 16rpx 20rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between; /* 两端对齐 */
  align-items: center; /* 垂直居中 */
}

/* 顶部城市栏样式 */
.city-bar {
  /* 移除固定定位 */
  background-color: #ffffff;
  padding: 10rpx 20rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  margin-left: auto;
}

.location-icon {
  margin-top: 1vw;
  width: 201px;
  object-fit: contain;
}

.city-text {
  font-size: 28rpx;
  color: #333333;
}

.product-card {
    padding: 15px;
    border-radius: 10px;
    margin: 10px;
    display: flex;
    background-color: #ffffff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    overflow: hidden; /* 添加这一行，确保内容不会溢出容器 */
    position: relative; /* 添加相对定位，用于对号图片的绝对定位 */
}

/* 添加选中样式 */
.selected-card {
    border: 2px solid #00C853; /* 绿色边框 */
}

.shop-right {
    flex: 1; /* 添加这一行，让shop-right占据剩余空间 */
    padding-left: 10px; /* 添加一些左边距，使内容不紧贴着图片 */
}

.shop-name {
    font-size: 18px;
    margin-bottom: 5px;
    font-weight: bold;
    color: #333;
    word-break: break-all; /* 添加这一行，确保长名称能够换行 */
}

.shop-address {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    font-size: 14px;
    color: #666;
    word-break: break-all; /* 添加这一行，确保长地址能够换行 */
}

.shop-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.shop-name {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.shop-tags {
    display: flex;
    gap: 5px;
    margin-bottom: 5px;
}

.tag {
    background-color: #e6f7ff;
    color: #1890ff;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
}

.shop-info {
    margin-bottom: 15px;
}

.shop-time, .shop-address, .shop-distance {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    font-size: 14px;
    color: #666;
}

.shop-info .iconfont {
    margin-right: 5px;
    color: #1890ff; 
}

.location-container {
    display: flex;
    justify-content: flex-end;
}

.location-btn {
    background-color: #1890ff;
    color: white;
    border: none;
    padding: 6px 15px;
    border-radius: 20px;
    font-size: 14px;
}

/* 城市选择弹窗样式 */
.city-selector-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.city-selector {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  z-index: 1000;
  max-height: 70vh;
  overflow: hidden;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #eeeeee;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.close-btn {
  font-size: 40rpx;
  color: #999999;
}

.city-list {
  padding: 20rpx;
  max-height: calc(70vh - 80rpx);
  overflow-y: auto;
}

.city-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  font-size: 28rpx;
  color: #333333;
}

.city-item:active {
  background-color: #f5f5f5;
}

</style>